package com.xxkj.drugtraceability.ui.patientlist

import android.app.Application
import android.content.Context
import android.content.Intent
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.xxhis.drugtraceability.base.BaseViewModel
import com.xxkj.drugtraceability.bean.DepartBean
import com.xxkj.drugtraceability.bean.PatientBean
import com.xxkj.drugtraceability.bean.PatientQuery
import com.xxkj.drugtraceability.ext.getSpValue
import com.xxkj.drugtraceability.net.Result
import com.xxkj.drugtraceability.ui.doctoradvicecollection.DoctorAdviceCollectionActivity
import com.xxkj.drugtraceability.utils.toast
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * author: zhoujingjin
 * created on: 2024/9/11 19:26
 * description:
 */
class PatientListViewModel(application: Application,private val patientListRepository: PatientListRepository):BaseViewModel(application) {
    var departList = MutableLiveData<List<DepartBean>?>()
    var uiState = MutableLiveData<UiState<String>>()
    var depart = ""
    var departName = MutableLiveData<String>()
    var page = 1
    //在院状态，默认01在院，02出院，非01就算出院
    var inState = MutableLiveData<String>("01")
    var loadMore = true
    var patientList = MutableLiveData<List<PatientBean>>()
     var dataList = mutableListOf<PatientBean>()
    var inHospState: String = ""
    /**
     * 获取科室列表
     */
    fun queryAllDept(){
        viewModelScope.launch(Dispatchers.Main) {
            withContext(Dispatchers.IO) {
               val depList = patientListRepository.queryAllDept()
                if (depList is Result.Success){
                    depList.data.data.add(0, DepartBean("","全部科室"))
                   val depart = depList.data.data.filter {
                        it.deptCode==depart
                    }
                    if (depart.isNotEmpty()){
                        departName.postValue(depart[0].deptName)
                    }
                    departList.postValue(depList.data.data)
                }else if (depList is Result.Error){
                    uiState.postValue(UiState(isError = depList.errorData?:depList.exception.message))
                }
            }
        }
    }

    /**
     * 获取病人列表
     */
    fun getPatientList(et:String){
        viewModelScope.launch(Dispatchers.Main) {
            withContext(Dispatchers.IO) {
                try {
                    if (page==1){
                        uiState.postValue(UiState(isRefresh = true))
                        dataList.clear()
                        loadMore = true
                    }
                    val depList = patientListRepository.queryPatientList(Gson().toJson(PatientQuery(et,depart,page,30,inHospState)))
                    if (depList is Result.Success){
                        if (dataList.size+depList.data.data.records.size>=depList.data.data.totalRecords){
                            loadMore = false
                        }
                        dataList.addAll(depList.data.data.records)
                     /*  val filter = dataList.filter {
                            inState.value == it.inHospState
                        }*/
                        patientList.postValue(dataList)
                        uiState.postValue(UiState(isRefresh = false))
                    }else if (depList is Result.Error){
                        uiState.postValue(UiState(isError = depList.errorData?:depList.exception.message))
                    }
                } catch (e: Exception) {
                }
            }
        }
    }
    /**
     * 获取病人某个时间的医嘱列表
     */
    fun getDoctorOrderedInfoList(barcode:String,date:String,context: Context){
        viewModelScope.launch(Dispatchers.Main) {
            withContext(Dispatchers.IO) {
                uiState.postValue(UiState(isLoading = true))
                val start = System.currentTimeMillis()
                val result = patientListRepository.getDoctorOrderedInfoList(date)
                if (result is Result.Success){
                   val spend = System.currentTimeMillis()-start
                    Log.e("耗时",spend.toString()+"ms")
                    //获取成功了
                    result.data.data.forEach {
                        it.dataForm = "02"
                        it.drugInfoList.forEach { druginfo->
                            druginfo.takeDrug = it.takeDrug
                            druginfo.presType = it.presType
                        }
                    }
                    if (result.data.data.isNotEmpty()){
                        context.startActivity(Intent(context, DoctorAdviceCollectionActivity::class.java)
                                .putExtra("patientId",result.data.data[0].patientId)
                                .putExtra("date",result.data.data[0].sendTime)
                                .putExtra("rxno",result.data.data[0].drugInfoList[0].rxno)
                        )
                        uiState.postValue(UiState(isLoading = false))
                    }else{
                        uiState.postValue(UiState(isLoading = false,isError = "未查到药品信息或该药品已完成发药，请确认"))
                    }
                }else if (result is Result.Error){
                    uiState.postValue(UiState(isLoading = false,isError = result.errorData?:result.exception.message))
                }
            }}
    }
}